package edu.corn.job.core.parser;

import edu.corn.common.context.ApplicationContextHolder;
import edu.corn.job.core.processor.ScheduleJobProcessor;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 这个类负责再项目启动之初，解析xml文件，将定时job都投入到引擎中执行。
 */
@Slf4j
public class ScheduleJobXmlParser implements JobParser {
    private List<ScheduleJobProcessor> processors;


    @Override
    public List<ScheduleJobProcessor> parse(InputStream resource) {
        if (processors == null) {
            processors = new ArrayList<ScheduleJobProcessor>();
            doParse(resource);
        }
        return processors;
    }

    void doParse(InputStream resource) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(TaskList.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            TaskList taskList = (TaskList) jaxbUnmarshaller.unmarshal(resource);
            for (Task task : taskList.getTask()) {
                ScheduleJobProcessor job = (ScheduleJobProcessor) ApplicationContextHolder.getBean(task.getClassName());
                job.setCount(task.getExecutionCount());
                job.setDelay(task.getDelay());
                job.setCronExpression(task.getCron());
                job.setInterval(task.getInterval());
                processors.add(job);
            }

        } catch (JAXBException e) {
            log.error(e.getMessage());
        }
    }
}
